package com.artisan.domain.service;

import com.artisan.domain.dto.PageDto;
import com.artisan.domain.dto.RoleDto;
import com.artisan.domain.dto.RoleGroupDto;
import com.artisan.domain.entity.MRole;
import com.artisan.domain.entity.MRoleGroup;
import com.artisan.domain.info.RoleInfo;
import com.artisan.domain.repositoryInterface.IRoleRepository;
import com.artisan.domain.serviceInterface.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色业务类
 */
@Service
public class RoleService implements IRoleService {
    @Autowired
    private IRoleRepository roleRepository;
    @Override
    public PageDto<RoleDto> findList(int pageIndex, int pageSize) {

        Pageable pageable = new QPageRequest(pageIndex, pageSize);
        Page<RoleInfo> page = this.roleRepository.findList(pageable);
        List<RoleDto> dtos = new ArrayList<>();
        page.getContent().forEach(
                model -> {
                    RoleDto dto = new RoleDto();
                    dto.setId(model.getRole().getId());
                    dto.setAddDate(model.getRole().getAddDate());
                    dto.setName(model.getRole().getName());
                    dto.setRoleGroupName(model.getRoleGroup().getName());
                    dtos.add(dto);
                });

        PageDto<RoleDto> result = new PageDto();
        result.setContent(dtos);
        result.setNumber(page.getNumber());
        result.setSize(page.getSize());
        result.setTotalElements(page.getTotalElements());

        return result;
    }

    @Override
    public RoleDto find(int id) {
        RoleInfo info = this.roleRepository.find(id);
        RoleDto dto = new RoleDto();
        dto.setId(info.getRole().getId());
        dto.setName(info.getRole().getName());
        dto.setRoleGroupName(info.getRoleGroup().getName());
        dto.setMenuIds(info.getRole().getMenuIds());

        return dto;
    }

    @Override
    public boolean update(RoleDto dto) {
        MRole model = this.roleRepository.findById(dto.getId()).get();
        model.setName(dto.getName());
        model.setRoleGroupId(dto.getRoleGroupId());
        this.roleRepository.saveAndFlush(model);

        return true;
    }

    @Override
    public boolean delete(int id) {
        this.roleRepository.deleteById(id);
        return true;
    }

    @Override
    public boolean update(int id, String menuIds) {
        MRole model = this.roleRepository.findById(id).get();
        model.setMenuIds(menuIds);
        this.roleRepository.saveAndFlush(model);
        return true;
    }
}
